import {
  post,
  validStringType,
  showToast,
  agentSave
} from '../../utils/util.js'
import Request from '../../utils/request.js';

let app = getApp()
let store = app.store
let timeId = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sessionKey:'',
    mobile: '', // 手机号
    code: '', //验证码
    activeCode: false, //验证码文本高亮
    activeBtn: false, //登录 btn 高亮
    getCodeText: '获取验证码', //发送验证码 文本
    isMobileRepeat: true //注册 或者 登录两种状态
  },

  bindMobileInput: function(e) {
    this.setData({
      mobile: e.detail.value
    })

    let mobile = this.data.mobile;
    if (!(/^1\d{10}$/.test(mobile))) {
      this.setData({
        activeCode: false
      })

      if (mobile.length >= 11) {
        wx.showToast({
          title: '手机号有误',
          icon: 'none',
          duration: 3000
        })
      }
    } else {
      !timeId && this.setData({
        activeCode: true
      })
    }
  },
  bindCodeInput: function(e) {
    this.setData({
      code: e.detail.value
    })

    let code = this.data.code;
    let mobile = this.data.mobile;

    if (code.length < 4) {
      this.setData({
        activeBtn: false
      })
    } else {
      this.setData({
        activeBtn: true
      })
    }
  },
  yanLoveBtn: function() {
    // let loveChange = this.data.loveChange;
    // console.log(loveChange)
    // let lovePhone = this.data.lovePhone;
    // console.log(lovePhone)
    let mobile = this.data.mobile;
    let isActiveCode = this.data.activeCode;
    let n = 59;
    let that = this;
    if (!isActiveCode) {
      return
    }
    if (!mobile) {
      showToast('text', '错误')
    } else {
      if (isActiveCode) {
        this.setData({
          activeCode: false
        })
        timeId = setInterval(function() {
          let str = '重新获取' + '(' + n + ')'
          that.setData({
            getCodeText: str
          })
          if (n <= 0) {
            that.setData({
              activeCode: true,
              getCodeText: '重新获取'
            })
            clearInterval(timeId);
            timeId = null;
          }
          n--;
        }, 1000);

        //获取验证码接口写在这里
        this.getCode();
      }
    }
  },
  submitForm(e) {

    var phone = this.data.mobile //电话
    var phoneCode = this.data.code //验证码
    let isActiveSubmit = this.data.activeBtn;
    console.log(isActiveSubmit);
    let self = this;

    if (isActiveSubmit) {
      //发送后端接口 并跳转
      wx.login({
        success(res) {
          if (res.code) {
            //手机号重复 走 login
            if (self.data.isMobileRepeat) {
              //发起网络请求
              self.goLogin(res.code);
            } else {
              //发起网络请求
              self.goRegster(res.code);
            }
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
  },
  
 
  doWxLogin() {
    console.log('doWxLogin=')
    wx.login({
      success: wxRes => {
        let code = wxRes.code
        let sessionKey = ''
        Request.postRequest('/wxAppletPay/getOpenId', { code: wxRes.code }).then(res => {
           sessionKey = JSON.parse(res.data.openId).session_key
           console.log('seeeeek' +  sessionKey)
           this.setData({
            sessionKey: sessionKey,
          });
          wx.setStorageSync('openid', JSON.parse(res.data.openId).openid)
          console.log('this.data=')
          console.log(this.data)
        })
        
      }
    })
  },

  wxLogin(e) {
    console.log(e.detail)
    wx.request({
      url: app.globalData.ENVIRONMENT_CONFIG.systemBaseUrl + '/api/wxUser/getLogin',
      data: {
        "type": "wx_mobile",
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData,
        sessionKey:this.data.sessionKey
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success(data) {
        console.log('data', data)
        if (data.data.code == 1) {
          // 注册成功
          console.log("登录成功");

          //更新 登录 信息
          try {
            // 本地存储 token
            wx.setStorageSync('token', data.data.data.token);
            wx.setStorageSync('userId', data.data.data.userId);
            wx.setStorageSync('imUserName', data.data.data.imUserName);
            wx.setStorageSync('imPassword', data.data.data.imPassword);
            wx.setStorageSync('mobile', data.data.data.mobile);
            wx.setStorageSync('imId', data.data.data.imId);
            wx.setStorageSync('doctorId', data.data.data.doctorId);
            wx.setStorageSync('roleList', data.data.data.roleList);

            // 更新 redux 本地数据
            store.dispatch({
              type: 'set_LoginData',
              data: {
                token: data.data.data.token,
                userId: data.data.data.userId,
                mobile: data.data.mobile,
                imUserName: data.data.data.imUserName,
                imPassword: data.data.data.imPassword,
                imId: data.data.data.imId
              }
            });
          } catch (e) {}

          wx.switchTab({
            url: '/pages/home/index/index'
          });
        } else {
          // 给出本地出错提示
          showToast('text', data.data.msg || '错误', { duration: 5000 })
        }
      },
      error() {
        // wx.hideLoading()
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.doWxLogin();
    //本地存储没有 token 跳转首页
    if (wx.getStorageSync("token")) {

      // 更新 redux 本地数据
      store.dispatch({
        type: 'set_LoginData',
        data: {
          token: wx.getStorageSync("token"),
          userId: wx.getStorageSync("userId"),
          mobile: wx.getStorageSync("mobile"),
          imUserName: wx.getStorageSync("imUserName"),
          imPassword: wx.getStorageSync("imPassword"),
          imId: wx.getStorageSync("imId"),
        }
      });

      wx.switchTab({
        url: '/pages/home/index/index'
      });
    }
    wx.setNavigationBarTitle({
      title: "注册登录" //页面标题为路由参数
    })
  },

  //免登陆跳转页面
  goAgreement() {
    console.log("111");
    wx.navigateTo({
      url: '/pages/login/agreement/agreement',
    })
  },

  //免登陆跳转页面
  goHome() {
    // console.log('登录中...');
    wx.switchTab({
      url: '/pages/home/index/index'
    });
    // console.log('登录结束');

    // console.log(store.getState().systemLoginData);

    // 登录信息
    // store.dispatch({
    //   type: 'set_LoginData',
    //   data: {
    //     token: '1',
    //     userId: '1',
    //     imUserName: '1',
    //     imPassword: '1'
    //   }
    // });

    // 取值在哪里
    // console.log(store.getState().systemLoginData);

    // 清除登录信息
    // store.dispatch({
    //   type: 'clear_LoginData'
    // });


    // 清除登录信息
    // console.log(store.getState().systemLoginData);
  },

  //获取验证码接口
  getCode() {
    let code = this.data.code;
    let mobile = this.data.mobile;
    let self = this;
    wx.showLoading({
      title: '获取验证码中',
    })
    wx.request({
      url: app.globalData.ENVIRONMENT_CONFIG.systemBaseUrl + '/api/wxUser/checkMobileAndSendCode',
      data: {
        mobile
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(data) {
        wx.hideLoading()
        // debugger
        if (data.data.code == 1) {
          // 注册成功
          console.log("获取验证码成功");
          wx.showToast({
            title: '获取验证码成功',
            icon: 'success',
            duration: 3000
          })
          self.setData({
            isMobileRepeat: false
          })

          // self.setData({
          //   activeBtn: true
          // })
        } else if (data.data.code == 2) { //手机号重复
          self.setData({
            isMobileRepeat: true
          })
          wx.showToast({
            title: '获取验证码成功',
            icon: 'success',
            duration: 3000
          })
        } else {
          // 给出本地出错提示
          showToast('text', data.data.msg || '错误')
        }

      },
      error() {
        wx.hideLoading()
      }
    })
  },

  //登录接口
  goLogin(wxCode) {
    // let code = this.data.code;
    let mobile = this.data.mobile;
    let sendCode = this.data.code;
    let self = this;
    wx.showLoading({
      title: '登录中...',
    })
    wx.request({
      url: app.globalData.ENVIRONMENT_CONFIG.systemBaseUrl + '/api/wxUser/getLogin',
      data: {
        code: wxCode,
        mobile,
        sendCode
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success(data) {
        wx.hideLoading()
        if (data.data.code == 1) {
          // 注册成功
          console.log("登录成功");

          //更新 登录 信息
          try {
            // 本地存储 token
            wx.setStorageSync('token', data.data.data.token);
            wx.setStorageSync('userId', data.data.data.userId);
            wx.setStorageSync('imUserName', data.data.data.imUserName);
            wx.setStorageSync('imPassword', data.data.data.imPassword);
            wx.setStorageSync('mobile', self.data.mobile);
            wx.setStorageSync('imId', data.data.data.imId);
            wx.setStorageSync('doctorId', data.data.data.doctorId);
            wx.setStorageSync('roleList', data.data.data.roleList);

            // 更新 redux 本地数据
            store.dispatch({
              type: 'set_LoginData',
              data: {
                token: data.data.data.token,
                userId: data.data.data.userId,
                mobile: self.data.mobile,
                imUserName: data.data.data.imUserName,
                imPassword: data.data.data.imPassword,
                imId: data.data.data.imId
              }
            });
          } catch (e) {}

          wx.switchTab({
            url: '/pages/home/index/index'
          });
        } else {
          // 给出本地出错提示
          showToast('text', data.data.msg || '错误', { duration: 5000 })
        }
      },
      error() {
        wx.hideLoading()
      }
    })
  },

  //注册接口
  goRegster(wxCode) {
    // let code = this.data.code;
    let code = wxCode;
    let mobile = this.data.mobile;
    let sendCode = this.data.code;
    let self = this;
    wx.showLoading({
      title: '登录中...',
    })

    wx.request({
      url: app.globalData.ENVIRONMENT_CONFIG.systemBaseUrl + "/api/wxUser/registerMobile",
      data: {
        mobile,
        code,
        sendCode
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(data) {
        wx.hideLoading()
        if (data.data.code == 1 || data.data.code == 0) {
          // 注册成功
          console.log("注册成功！");
          self.goLogin();

          // 记录推广二维码
          agentSave({
            agentNum: app.globalData.agentNum,
            mobile: mobile,
            agentType: 1, // 注册
            userId: data.data.data.info.userId
          })
        } else {
          // 给出本地出错提示
          showToast('text', data.data.msg || '错误')
        }
      },
      error() {
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(timeId)
    timeId = null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})
